<template>
  <view class="container">
    <my-navbar-top></my-navbar-top>
    <view class="login">
      <!-- 表单 -->
      <view class="ef-form" style="flex: 1">
        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">联系人</view>
          </view>
          <view class="ef-form__item-body">
            <uni-easyinput v-model="valiFormData.realname" primaryColor="#c9a063" :inputBorder="false"
              placeholder="请输入您的姓名" />
            <button class="auth-phone" @click="openAuthHeadimg">
              授权微信昵称及头像
            </button>
          </view>
        </view>
        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">手机号</view>
          </view>
          <view class="ef-form__item-body">
            <uni-easyinput type="number" maxlength="11" v-model="valiFormData.telephone" :inputBorder="false"
              primaryColor="#c9a063" placeholder="请输入您的手机号" />
            <button class="auth-phone" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">
              授权手机号
            </button>
          </view>
        </view>
        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">省市区</view>
            <view @click="handleChooseAddress" class="auth-phone">
              授权微信地址
            </view>
          </view>
          <view class="ef-form__item-body address-picker" style="background: transparent; padding: 0">
            <picker mode="region" @change="handlePickerChange" style="margin-right: 12rpx">
              <view class="address-picker-item">
                <text v-if="valiFormData.province" style="color: #545454">{{
                  valiFormData.province || '省'
                  }}</text>
                <text v-else style="color: #999">省</text>
                <image src="@/static/images/gray-right.png" mode="widthFix" />
              </view>
            </picker>

            <picker mode="region" @change="handlePickerChange" style="margin-right: 12rpx">
              <view class="address-picker-item">
                <text v-if="valiFormData.city" style="color: #545454">{{
                  valiFormData.city || '市'
                  }}</text>
                <text v-else style="color: #999">市</text>
                <image src="@/static/images/gray-right.png" mode="widthFix" />
              </view>
            </picker>
            <picker mode="region" @change="handlePickerChange">
              <view class="address-picker-item">
                <text v-if="valiFormData.area" style="color: #545454">{{
                  valiFormData.area || '区'
                  }}</text>
                <text v-else style="color: #999">区</text>
                <image src="@/static/images/gray-right.png" mode="widthFix" />
              </view>
            </picker>
          </view>
        </view>

        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">详细地址</view>
          </view>
          <view class="ef-form__item-body">
            <uni-easyinput v-model="valiFormData.address" :inputBorder="false" primaryColor="#c9a063"
              placeholder="请输入您的详细地址" />
          </view>
        </view>
        <view style="display: flex; flex-direction: row; gap: 20rpx">
          <view class="ef-form__item" style="width: 48%">
            <view class="ef-form__item-header">
              <view class="title">所属公司（选填）</view>
            </view>
            <view class="ef-form__item-body">
              <uni-easyinput v-model="valiFormData.company" :inputBorder="false" primaryColor="#c9a063"
                placeholder="请填写公司名称" />
            </view>
          </view>
          <view class="ef-form__item" style="flex: 1">
            <view class="ef-form__item-header">
              <view class="title">业务类型（选填）</view>
            </view>
            <view class="ef-form__item-body address-picker" style="background: transparent; padding: 0">
              <picker mode="selector" :range="businessOptions" :value="valiFormData.business_type"
                @change="handleBusinessChange" style="width: 100%">
                <view class="address-picker-item">
                  <text v-if="valiFormData.business_type" style="color: #545454">{{ valiFormData.business_type || '业务类型'
                    }}</text>
                  <text v-else style="color: #999">业务类型</text>
                  <image src="@/static/images/gray-right.png" mode="widthFix" />
                </view>
              </picker>
            </view>
          </view>
        </view>
        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">客户编号（选填）</view>
          </view>
          <view class="ef-form__item-body">
            <uni-easyinput v-model="valiFormData.customer_id" :inputBorder="false" primaryColor="#c9a063"
              placeholder="老客户专属编号，填写将自动获取专属折扣" />
          </view>
        </view>

        <!-- 我已阅读并同意《用户协议》和《隐私政策》 -->
        <view class="agreement" @click="handleAgreement">
          <view class="agreement-checkbox" :class="{ checked: agreementChecked }"></view>
          <text>我已阅读并同意</text>
          <text class="agreement-link" @click="openPrivacyPopup">隐私协议和使用条款</text>
        </view>
      </view>
      <view class="address-add">
        <button class="primary-button" @click="save">
          {{ valiFormData.telephone ? '保存' : '立即注册' }}
        </button>
      </view>
    </view>
    <!-- 弹框 -->
    <uni-popup ref="authPopup" style="z-index: 999">
      <view class="auth-popup">
        <image class="auth-popup-logo" src="/static/images/logo.png" mode="widthFix" />
        <view class="auth-popup-title">获取你的昵称、头像</view>
        <view class="auth-popup-input">
          <view>头像</view>
          <button class="img" open-type="chooseAvatar" @chooseavatar="getChooseavatar">
            <image style="width: 84rpx" :src="valiFormData.headimgurl || '/static/images/default.png'"
              mode="widthFix" />
          </button>
        </view>
        <view class="auth-popup-input">
          <view>昵称</view>
          <view class="inp-box">
            <input class="inp" type="nickname" v-model="valiFormData.nickname" placeholder="请输入昵称" />
          </view>
        </view>
        <!-- 提示 -->
        <view class="auth-popup-tip">
          昵称限2-16个字符，一个汉字为2个字符
        </view>
        <view class="auth-popup-footer">
          <button class="primary-button" @click="confirmAuth">确认</button>
        </view>
      </view>
    </uni-popup>
    <!-- 隐私政策 -->
    <uni-popup ref="privacyPopup" style="z-index: 999">
      <view class="privacy-popup">
        <agreement style="width: 100%;" @close="closePrivacyPopup"></agreement>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import Agreement from '@/components/agreement/index.vue'
export default {
  name: 'register',
  components: {
    Agreement
  },
  data() {
    return {
      //headimgurl: '', // 头像
      // 校验表单数据
      valiFormData: {
        realname: '', // 姓名
        telephone: '', // 手机号
        nickname: '', // 昵称
        headimgurl: '', // 头像
        headimgurl_file_name: '', // 头像
        province: '', // 省
        city: '',
        area: '',
        address: '', // 详细地址
        company: '', // 公司
        business_type: 0, // 业务类型
        customer_id: '', // 地址信息
      },
      businessOptions: ['定制店', '加工厂', '男装品牌', '女装品牌', '其他'],
      agreementChecked: false, // 协议是否选中
    }
  },
  mounted() {
    this.initData()

  },
  methods: {
    openPrivacyPopup() {
      this.$refs.privacyPopup.open('center')
    },
    closePrivacyPopup() {
      this.$refs.privacyPopup.close()
    },
    initData() {
      let telephone = uni.getStorageSync('userInfo').telephone || ''
      if (telephone) {
        let userInfo = uni.getStorageSync('userInfo') || {}
        for (let key in this.valiFormData) {
          this.valiFormData[key] = userInfo[key] || ''
        }
      }
    },
    // / 获取头像
    getChooseavatar(e) {
      console.log(JSON.stringify(e.detail))
      let url = 'https://xcx.essence-stock.com/upload/index'
      // 上传图片
      wx.uploadFile({
        filePath: e.detail.avatarUrl,
        name: 'file',
        header: {
          'content-type': 'application/json',
          Authorization: wx.getStorageSync('access_token'),
        },
        url: url,
        success: (res) => {
          let res1 = JSON.parse(res.data)
          this.valiFormData.headimgurl_file_name = res1.data.file_name || ''
          this.valiFormData.headimgurl = res1.data.url || ''
          console.log(this.valiFormData.headimgurl, '头像地址')
        },
        fail: (err) => {
          console.log('Url:', url, ' err:', err)
        },
      })
    },
    openAuthHeadimg() {
      this.$refs.authPopup.open('bottom')
    },
    confirmAuth() {
      this.$refs.authPopup.close()
    },
    // 授权微信地址
    handleChooseAddress(e) {
      wx.chooseAddress({
        success: (res) => {
          console.log(res)
          this.valiFormData.realname = res.userName
          this.valiFormData.province = res.provinceName
          this.valiFormData.city = res.cityName
          this.valiFormData.area = res.countyName
          this.valiFormData.address = res.detailInfo
        },
        complete: (res) => {
          console.log(res, 'complete')
        },
      })
    },
    /**
     * 表单校验
     */
    formValidate() {
      return new Promise((resolve, reject) => {
        let { realname, telephone, address, province, city, area } =
          this.valiFormData
        if (!realname) {
          uni.showToast({
            title: '请输入姓名',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!telephone) {
          uni.showToast({
            title: '请输入手机号',
            icon: 'none',
          })
          resolve(false)
          return
        }
        // 校验手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(telephone)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!address) {
          uni.showToast({
            title: '请输入地址',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!province) {
          uni.showToast({
            title: '请选择省',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!city) {
          uni.showToast({
            title: '请选择市',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!area) {
          uni.showToast({
            title: '请选择区',
            icon: 'none',
          })
          resolve(false)
          return
        }
        // 如果协议未选中
        if (!this.agreementChecked) {
          uni.showToast({
            title: '请同意用户协议和隐私政策',
            icon: 'none',
          })
          resolve(false)
          return
        }
        resolve(true)
      })
    },
    /**
     * 获取手机号
     */
    decryptPhoneNumber(e) {
      console.log(e)
      let { errMsg, code = null } = e.detail
      if (errMsg == 'getPhoneNumber:ok') {
        this.$api
          .decodePhone({
            code,
          })
          .then((res) => {
            console.log(res, '---')
            this.valiFormData.telephone = res.data.phoneNumber || ''
          })
      }
    },
    cancel() {
      uni.navigateBack()
    },
    save() {
      this.formValidate().then((res) => {
        console.log(res)
        if (!res) return
        let params = {
          ...this.valiFormData,
        }
        this.$api.update_info(params).then((res) => {
          console.log(res)
          if (res.code == 0) {
            uni.showToast({
              title: '注册成功',
              icon: 'success',
            })
            // 保存用户信息到本地
            uni.setStorageSync('userInfo', res.data)
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/user/index',
              })
            }, 500)
          }
        })
      })
    },
    handleAgreement() {
      this.agreementChecked = !this.agreementChecked
    },
    // 省市区
    handlePickerChange(e) {
      console.log(e)
      let { value, code } = e.detail
      this.valiFormData.province = value[0]
      this.valiFormData.city = value[1]
      this.valiFormData.area = value[2]
    },

    // 业务类型选择
    handleBusinessChange(e) {
      console.log(e)
      let { value } = e.detail
      this.valiFormData.business_type = this.businessOptions[value] || ''
      console.log(this.valiFormData.business_type)
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';

.privacy-popup {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
</style>
